var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');

var indexRouter = require('./routes/index.js');
var usersRouter = require('./routes/users');
const questionRouter = require('./routes/question.js');
const questionCategoryRouter = require('./routes/questionCategory.js');
const feedbackRouter = require('./routes/feedback.js');
const checkinRouter = require('./routes/checkin.js');
const collectionRouter = require('./routes/collection.js');
const battleRouter = require('./routes/battle.js');
const wrongQuestionsRouter = require('./routes/wrongQuestions');
const questionCommentRouter = require('./routes/questionComment');
const questionSet = require('./routes/questionSet.js')

var app = express();
const port = process.env.PORT || 7332;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/qa/user', usersRouter);
app.use('/qa/question', questionRouter);
app.use('/qa/questionCategory', questionCategoryRouter);
app.use('/qa/feedback', feedbackRouter);
app.use('/qa/checkin', checkinRouter);
app.use('/qa/collection', collectionRouter);
app.use('/qa/battle', battleRouter);
app.use('/qa/wrong', wrongQuestionsRouter);
app.use('/qa/comment', questionCommentRouter);
app.use('/qa/questionSet',questionSet)

// catch 404 and forward to error handler
app.use(function (err,req, res, next) {
  console.log(err)
  // 直接返回 JSON 响应
  res.status(404).json({
    code: 404,
    msg: 'Resource not found'
  });
});

// error handler
app.use(function (err, req, res, next) {
  // 设置响应状态码
  res.status(err.status || 500);

  // 返回 JSON 响应
  res.json({
    code: err.status || 500,
    msg: err.message
  });
});

// 监听端口
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

module.exports = app;
